//DatabaseHelper class - connects to the internal android sqlite database using the SQLiteAssetHelper
//This database contains all the card info for the game.

package com.cah.library;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseHelper extends SQLiteAssetHelper
{
	private static final String DATABASE_NAME = "cards.3.db";
	private static final int DATABASE_VERSION = 1;

	//Constructor
	public DatabaseHelper(Context context)
	{
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	//getWhiteTexts - Given a list of ids, a cursor is returned that contains all of those ids and their associated
	//card texts from the white card table
	public Cursor getWhiteTexts(int[] ids)
	{
		SQLiteDatabase db = getReadableDatabase();
		String whereClause = "(";
		
		for(int i=0;i<ids.length;i++)
		{
			if(i>0)
			{
				whereClause += ",";
			}
			whereClause += "\"" + Integer.toString(ids[i]) + "\"";
		}
		whereClause += ")";
		
		return db.rawQuery("SELECT _id, text FROM white_cards WHERE _id in " + whereClause, null);
	}
	
	//getBlackCard - Given an id, a cursor is returned that contains a single row with the id and its associated 
	//black card text and number of white cards to be picked.
	public Cursor getBlackCard(int id)
	{
		SQLiteDatabase db = getReadableDatabase();
		Log.e("id", Integer.toString(id));
		return db.rawQuery("SELECT _id, text, pick FROM black_cards WHERE _id = \"" + Integer.toString(id) + "\"", null);
	}
	
	//Get the user key from the database
	public String getUserKey()
	{
		SQLiteDatabase db = getReadableDatabase();
		Cursor c = db.rawQuery("SELECT userKey FROM userInfo WHERE _id = 0", null);
		String userKey = "";
		if(c.moveToFirst())
		{
			userKey = c.getString(0);
		}
		
		db.close();
		return userKey;
	}
	
	//Set the userkey
	public void setUserKey(String userKey)
	{
		String currentUserKey = getUserKey();
		if(currentUserKey.length()==0)
		{
			SQLiteDatabase db = getWritableDatabase();
			ContentValues values = new ContentValues();
			values.put("_id", 0);
			values.put("userKey", userKey);
			db.insert("userInfo", null, values);
			db.close();
			return;
		}
		else if(currentUserKey.equals(userKey))
		{
			return;
		}
		
		SQLiteDatabase db = getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("userKey", userKey);
		db.update("userInfo", values, null, null);
		db.close();
	}
	
	public void unsetUserKey()
	{
		SQLiteDatabase db = getWritableDatabase();
		db.delete("userInfo", null, null);
		db.close();
	}
}
